<?php

namespace oa\controllers;

use oa\services\MenuService;
use oa\services\UserService;
use Yii;
use yii\web\Response;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UnauthorizedHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\BadRequestHttpException;
use yii\helpers\Json;

use common\services\SysConfigService;

// 基础控制器
class BaseController extends Controller
{

    public $result;

    /**
     * 脚本执行开始时间
     * @var [type]
     */
    public $script_start_at;

    public $visit_url;
    public $visit_menu;

    public function init()
    {
        parent::init();

        $this->script_start_at = microtime(true);
    }

    public function beforeAction($action)
    {
        // 设置ajax请求的返回类型是json
        if ($this->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
        }

        // 判断是否是公开的请求地址
        $controller = Yii::$app->controller->id;
        if ($controller == 'public') {
            if (!Yii::$app->user->isGuest) {
                $this->redirect('/');
                Yii::$app->end();
            }
        } else {
            // 校验登录
            if (Yii::$app->user->isGuest) {
                $this->redirect('/login');
                Yii::$app->end();
            }

            $this->visit_url = Yii::$app->requestedRoute;
            if (empty($this->visit_url)) {
                $this->visit_url = Yii::$app->defaultRoute . '/' . Yii::$app->controller->defaultAction;
            }

            // 查询菜单
//            if (Yii::$app->session->has('menus')) {
//                $menus = Yii::$app->session->get('menus');
//            } else {
            $menus = MenuService::getAllByUid();
            Yii::$app->session->set('menus', $menus);
//            }

            if ($controller != 'site' && !$this->checkPriv()) {
                $this->throwException(403);
            }

            // 设置页面数据信息 如：菜单，导航，页面标题
            $this->setViewData();
        }
        return parent::beforeAction($action);
    }

    public function afterAction($action, $result)
    {
        // 记录访问日志
        \oa\services\LogUserVisitService::add($this->script_start_at, $this->visit_url);

        if ($this->request->isAjax || $this->request->isPost) {
            if (is_bool($result)) {
                $this->json($this->result);
            } elseif (is_array($result)) {
                $this->json($result);
            }
        }
        return parent::afterAction($action, $result);
    }

    public function json($data)
    {
        exit(Json::encode($data));
    }

    public function ok($msg = '操作成功', $data = [], $code = 0)
    {
        $this->result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        return true;
    }

    public function err($msg = '操作失败，请重试', $data = [], $code = -1)
    {
        $this->result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        return false;
    }

    // 设置view参数
    protected function setViewParam($key, $val)
    {
        $this->view->params[$key] = $val;
    }

    // 渲染页面
    public function fetch($data = [], $type = 1, $view = '')
    {
        switch ($type) {
            case 1: $renderFunc = 'render'; break;
            case 2: $renderFunc = 'renderPartial'; break;
            case 3: $renderFunc = 'renderAjax'; break;
            
            default: $renderFunc = 'render'; break;
        }
        empty($view) && $view = $this->action->id;
        return $this->$renderFunc($view, $data);
    }

    // 校验访问权限
    public function checkPriv()
    {
        return true;
        // 权限控制开关
//        $auth_status_config = SysConfigService::one('auth.status');
//        if ($auth_status_config != 1) {
//            return true;
//        }

        $menus = Yii::$app->session->get('menus');
        foreach ($menus as $v) {
            $actions = explode("|", $v['actions']);
            if ($v['url'] == $this->visit_url || in_array(Yii::$app->controller->id, $actions) || in_array($this->visit_url, $actions)) {
                $this->visit_menu = $v;
                return true;
            }
        }
        return false;
    }

    // 设置页面信息 如：菜单，导航，页面标题
    public function setViewData()
    {
        if ($this->request->isAjax) {   // ajax 请求
            $this->layout = false;
        }
        if (!$this->request->isAjax && !$this->layout && $this->layout !== false) {
            $view_title = '';    // 标题
            $breadcrumbs = [];    // 导航
            $visit_menu_id = 0;    // 当前访问菜单路径id

            if (Yii::$app->controller->id != 'site') {
                $visit_menu_id = $this->visit_menu['id'];
            }
            $this->setViewParam('menus', MenuService::render($visit_menu_id));    // 页面菜单HTML
        }
    }

    // 生成并设置页面导航
    public function setViewBreadcrumbs($breadcrumbs = [])
    {
        $homeLink = [
            'label' => '首页', 
            'url' => '/', 
            'template' => "<li><i class='ace-icon fa fa-home home-icon'></i> {link}</li>\n"
        ];
        array_unshift($breadcrumbs, $homeLink);
        $this->setViewParam('breadcrumbs', $breadcrumbs); // 页面导航
    }

    public function input($name, $default = null)
    {
        if ($this->request->isPost) {
            return $this->request->post($name, $default);
        }
        return $this->request->get($name, $default);
    }

    public function throwException($code = 400, $message = '')
    {
        switch ($code) {
            case 403:
                throw new NotFoundHttpException($message ? $message : '对不起，您没有访问权限');
                break;
            case 404:
                throw new NotFoundHttpException($message ? $message : '对不起，您访问的页面不存在');
                break;
            
            default:
                throw new BadRequestHttpException($message ? $message : '您的操作有误，请重试');
                break;
        }
    }


}
